<template>
  <div class="axiom-search-toolbar">
    <!-- 字段区 -->
    <div class="axiom-search-toolbar__fields">
      <div v-for="field in fields" :key="field.model" class="axiom-search-toolbar__field-item">
        <label v-if="field.label" class="axiom-search-toolbar__label">{{ field.label }}</label>
        <el-input
          v-if="field.type === 'input'"
          v-model="searchQuery[field.model]"
          :placeholder="field.placeholder || `请输入${field.label}`"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-select
          v-if="field.type === 'select'"
          v-model="searchQuery[field.model]"
          :placeholder="field.placeholder || `请选择${field.label}`"
          clearable
        >
          <el-option
            v-for="option in field.options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </div>
    </div>

    <!-- 操作区 -->
    <div class="axiom-search-toolbar__actions">
      <AxiomButton type="primary" icon="search" @click="handleSearch">搜索</AxiomButton>
      <AxiomButton icon="refresh" @click="handleReset">重置</AxiomButton>
    </div>
  </div>
</template>

<script>
// 直接从 element-plus 导入原子组件
import { ElInput, ElSelect, ElOption } from 'element-plus';
import AxiomButton from '../common/AxiomButton.vue';

export default {
  name: 'AxiomSearchToolbar',
  components: { ElInput, ElSelect, ElOption, AxiomButton },
  props: {
    fields: {
      type: Array,
      required: true,
      default: () => [],
    },
  },
  data() {
    const searchQuery = {};
    if (Array.isArray(this.fields)) {
      this.fields.forEach(field => {
        searchQuery[field.model] = field.defaultValue ?? undefined;
      });
    }
    return {
      searchQuery,
    };
  },
  watch: {
    fields: {
      immediate: true,
      handler(newFields) {
        const query = {};
        if (Array.isArray(newFields)) {
          newFields.forEach(field => {
            query[field.model] = field.defaultValue ?? undefined;
          });
        }
        this.searchQuery = query;
      },
    },
  },
  methods: {
    handleSearch() {
      const activeQuery = {};
      for (const key in this.searchQuery) {
        const value = this.searchQuery[key];
        if (value !== '' && value !== null && value !== undefined) {
          activeQuery[key] = value;
        }
      }
      this.$emit('search', activeQuery);
    },
    handleReset() {
      const query = {};
      this.fields.forEach(field => {
        query[field.model] = field.defaultValue ?? undefined;
      });
      this.searchQuery = query;
      this.$emit('search', {});
    },
  },
};
</script> 